package websocket

import (
	"fmt"
	"github.com/gorilla/websocket"
	"github.com/satori/go.uuid"
	"log"
	"net/http"
	"net/url"
	"time"
)

const (
	DEFAULT_RECONNECT = 1
)

/*客户端连接状态控制标志位*/
var (
	status    = make(chan bool, 1)
	netStatus = false
)

func GetNetStatus() bool {
	return netStatus
}

func StartConnect(ip, port, wsHandleUrl string, interval time.Duration) (conn *Connection) {
	status <- false
	for {
		select {
		case s := <-status:
			if !s {
				netStatus = false
				conn, _ = connect(ip, port, wsHandleUrl, interval)
			} else {
				netStatus = true
			}
		}
		time.Sleep(time.Second)
	}
}

func connect(ip, port, wsHandleUrl string, interval time.Duration) (conn *Connection, err error) {
	var (
		wsConn *websocket.Conn
		resp   *http.Response
	)
	u := url.URL{Scheme: "ws", Host: ip + ":" + port, Path: wsHandleUrl}
	log.Printf("connecting websocket server 【%s】", u.String())
	uid, _ := uuid.NewV4()
	clientId := uid.String()
	header := make(http.Header)
	header.Add("clientId", clientId)
	if wsConn, resp, err = websocket.DefaultDialer.Dial(u.String(), header); err != nil {
		log.Println("connecting websocket err:", err)
		status <- false
	} else {
		if conn, err = InitConnection(wsConn, false, header); err != nil {
			fmt.Println("connecting InitConnection err:", err)
			status <- false
		} else {
			status <- true
			serverId := resp.Header.Get("serverId")
			log.Printf("websocket clientId:[%s] connected serverId:[%s] successful......", clientId, serverId)
			go func() {
				t := time.NewTicker(interval)
				for {
					select {
					case <-t.C:
						if err := conn.WriteMessage([]byte("clientId:" + clientId + " heartbeat")); err != nil {
							status <- false
							return
						}
						log.Printf("clientId:[%s] send heartbeat......", clientId)
					case <-conn.CloseChan():
						log.Printf("clientId:[%s] send hearbeat error,connection closed", clientId)
						status <- false
						return
					}

				}
			}()
		}
	}
	return
}
